package org.slg.oracleproject.controller;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slg.oracleproject.entity.RolePermission;
import org.slg.oracleproject.respones.CommonResult;
import org.slg.oracleproject.service.RolePermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.slg.oracleproject.entity.Permission;
import org.slg.oracleproject.service.PermissionService;
import org.springframework.web.bind.annotation.RestController;
import java.io.Serializable;
import java.util.List;

/**
 *  控制层。
 *
 * @author 沙龙果
 * @since 2025年09月23日
 */
@RestController
@RequestMapping("/permission")
@Tag(name = "权限模块",description = "暂未开发")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RolePermissionService rolePermissionService;

    /**
     * 接口权限数据添加。
     *
     * @param permission 
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("/save")
    @Operation(summary = "接口权限数据添加", description = "接口权限数据添加")
    @Transactional // 开启事务，确保操作原子性
    public CommonResult save(@RequestBody Permission permission) {
        // 保存Permission（失败时抛出异常，触发事务回滚）
        boolean saveSuccess = permissionService.save(permission);
        if (!saveSuccess) {
            throw new MybatisPlusException("权限数据保存失败"); // 抛出异常，事务回滚
        }
        // 获取自增ID（失败时抛出异常）
        Integer permId = permission.getId();
        if (permId == null) {
            throw new MybatisPlusException("权限保存成功，但未获取到自增ID"); // 触发回滚
        }
        // 保存角色-权限关联关系（失败时抛出异常）
        RolePermission rolePermission = new RolePermission();
        rolePermission.setRoleId(1); // 注意：建议不要硬编码，可从参数或上下文获取
        rolePermission.setPermId(permId);
        boolean rpSaveSuccess = rolePermissionService.save(rolePermission);
        if (!rpSaveSuccess) {
            throw new MybatisPlusException("角色与权限关联关系保存失败"); // 触发回滚
        }
        // 所有操作成功，事务自动提交
        return CommonResult.success("角色接口权限添加成功！");
    }

}
